package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.Neusoft.service.NeusoftEmployeeChangeService;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.constVo.ContractConst;
import com.zhangtai.modules.constVo.SalaryConst;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.ContractRecordDao;
import com.zhangtai.modules.dao.EmployeeInfoDao;
import com.zhangtai.modules.dao.PromotionBatchGroupDao;
import com.zhangtai.modules.dao.PromotionDao;
import com.zhangtai.modules.dto.*;
import com.zhangtai.modules.entity.contract.ContractMangerEntity;
import com.zhangtai.modules.entity.contract.ContractRecordEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.PromotionEntity;
import com.zhangtai.modules.entity.promotion.PromotionBatchEntity;
import com.zhangtai.modules.entity.promotion.PromotionBatchGroupEntity;
import com.zhangtai.modules.entity.regular.RegularBpmEntity;
import com.zhangtai.modules.entity.salary.SalaryChangeEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.contract.ContractMangerService;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.promotion.PromotionBatchGroupService;
import com.zhangtai.modules.service.promotion.PromotionBatchService;
import com.zhangtai.modules.service.promotion.PromotionService;
import com.zhangtai.modules.service.regular.RegularBpmService;
import com.zhangtai.modules.service.salary.SalaryChangeService;
import com.zhangtai.modules.vo.*;
import com.zhangtai.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@Api(tags="员工晋升接口")
@Slf4j
@RequestMapping("/promotion")
public class PromotionController {

    @Autowired
    private PromotionDao promotionDao;
    @Autowired
    private BaseMssqlServiceImpl commonService;

    @Autowired
    private EmployeeInfoService employeeInfoService;

    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private PromotionService promotionService;
    @Autowired
    private LoginController loginController;
    @Autowired
    private SalaryController salaryController;
    @Autowired
    private JobController jobController;
    @Autowired
    private RegularBpmService regularBpmService;
    @Autowired
    private CommonController commonController;
    @Autowired
    private PromotionBatchService promotionBatchService;
    @Autowired
    private PromotionBatchGroupService promotionBatchGroupService;
    @Autowired
    private PromotionBatchGroupDao promotionBatchGroupDao;
    @Autowired
    private SalaryChangeService salaryChangeService;
    @Autowired
    private ContractController contractController;
    @Autowired
    private ContractRecordDao contractRecordDao;
    @Autowired
    private ContractMangerService contractMangerService;
    @Autowired
    private NeusoftEmployeeChangeService neusoftEmployeeChangeService;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;


//    @Transactional
    @GetMapping("/findPromotionByUserCode")
    @ApiOperation(value="根据工号查询晋级信息")  // 请求参数需要加 @RequestParam 注解  和参数描述注解@ApiParam
    @PreAuthorize("hasAuthority('emp:plgljj:get')")
    public R<PromotionDto> findPromotionByUserCode(@ApiParam(value="员工工号",required=true) @RequestParam(value = "userCode",required = true) String userCode,
                                                       @RequestParam(value = "promotionKind",required = true) Integer promotionKind,HttpServletRequest request)throws  Exception{


        /**
         * 不需要查询历史晋升记录，只需要把他的基本信息带出来，晋升后的字段留给前端填
         */
//        List<PromotionEntity> promotionEntities = promotionDao.selectList(new QueryWrapper<PromotionEntity>().eq("code", userCode).eq("is_delete", 0)
//        .orderByDesc("create_time"));
//        PromotionEntity promotionEntity=null;
//        if (!CollectionUtils.isEmpty(promotionEntities)){
//             promotionEntity = promotionEntities.get(0);
//             return R.ok(promotionEntity);
//        }
        /**
         * 先去mysql主库中查询员工主表，如果查不到再去mssql中查找
         */
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code", userCode).eq("is_delete", 0));

        if (ObjectUtils.isEmpty(employeeInfoEntity)){
            employeeInfoEntity = commonService.finEmpFromMssqlByCode(userCode);
            setJobLevel(employeeInfoEntity); //封装职级
        }

        if (ObjectUtils.isEmpty(employeeInfoEntity)){
            return R.ok();
        }
        PromotionDto promotionEntity= new PromotionDto();
        promotionEntity.setOid(employeeInfoEntity.getOid());
        promotionEntity.setCode(employeeInfoEntity.getCode());
        promotionEntity.setName(employeeInfoEntity.getName());
        Long jobId = employeeInfoEntity.getJobId();
        promotionEntity.setBeforeJobId(jobId); //晋升前岗位id
        String jobName = jobController.getJobName(jobId);
//        JobDto jobById = commonService.findJobById(jobId);
//        if (ObjectUtils.isEmpty(jobById)){
//            return R.error("JobDto查询为空");
//        }
        promotionEntity.setBeforeJobName(jobName);//晋升前岗位

        Long unitId = employeeInfoEntity.getUnitId();//晋升前部门id
        promotionEntity.setBeforeUnitId(unitId);
        String beforeUnit = jobController.getOrgNameById(unitId);
//        OrgEntity orgById = commonService.findOrgById(unitId);
//        if (ObjectUtils.isEmpty(orgById)){
//            return R.error("OrgEntity查询为空");
//        }
        promotionEntity.setBeforeUnitName(beforeUnit);//晋升前部门
        Long orgId = employeeInfoEntity.getOrgId();
        promotionEntity.setBeforeOrgId(orgId); //晋升前公司id
        String beforeOrg = jobController.getOrgNameById(orgId);
//        OrgEntity orgEntity = commonService.findOrgById(orgId);
//        if (ObjectUtils.isEmpty(orgEntity)){
//            return R.error("晋升前公司为空");
//        }
        promotionEntity.setBeforeOrgname(beforeOrg); //晋升前公司

        Long jobLevelId = employeeInfoEntity.getJobLevelId();
        String jobLevelNameById = jobController.getJobLevelNameById(jobLevelId);
//        JobLevelDto jobLevelById = commonService.findJobLevelById(jobLevelId);
//        if (ObjectUtils.isEmpty(jobLevelById)){
//            return R.error("JobLevelDto为空");
//        }
        promotionEntity.setBeforeJobLevelId(jobLevelId);
        promotionEntity.setBeforeJobLevel(jobLevelNameById);
        promotionEntity.setPromotionKind(promotionKind);


        /**
         * 仅做查询 不做新增
         */
        return R.ok(promotionEntity);


    }

    private void setJobLevel(EmployeeInfoEntity employeeInfoEntity) {
        Long managementJoblevelId = employeeInfoEntity.getManagementJoblevelId();
        Long professionJoblevelId = employeeInfoEntity.getProfessionJoblevelId();
        if (!ObjectUtils.isEmpty(managementJoblevelId)){
            employeeInfoEntity.setJobLevelType(2);
            employeeInfoEntity.setJobLevelId(managementJoblevelId);
        }else {
            employeeInfoEntity.setJobLevelType(1);
            employeeInfoEntity.setProfessionJoblevelId(professionJoblevelId);
        }
    }


    @PostMapping("/updatePromotion")
    @ApiOperation(value="修改晋级信息")
    @SysAuthorityLog(value = "修改晋级信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:plgljj:update')")
    public R updatePromotion(@RequestBody @Valid PromotionVo promotionVo, HttpServletRequest request)throws Exception{
        PromotionEntity promotionEntity = BeanUtilsMabach.doToDto(promotionVo, PromotionEntity.class);

        JSONObject  user = loginController.getUserInfo(request).getData();
        //获取申请人信息
        String userCode = user.getString("usercode");
        String name = user.getString("name");
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectById(promotionEntity.getOid());
        if(employeeInfoEntity==null){
            employeeInfoEntity = commonService.finEmpFromMssqlByCode(promotionVo.getCode());
        }
        //判断是否为有该部门的权限
        R checkR = loginController.checkOrgPermission(request,employeeInfoEntity.getUnitId(),true);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        Date createTime = new Date();
        //填充申请人信息
        promotionEntity.setApplier(name);
        promotionEntity.setApplierCode(userCode);
        //填充员工当前工作信息
        promotionEntity.setBeforeUnitId(employeeInfoEntity.getUnitId());
        promotionEntity.setBeforeOrgId(employeeInfoEntity.getOrgId());
        promotionEntity.setBeforeJobId(employeeInfoEntity.getJobId());
        promotionEntity.setBeforeJobLevelId(employeeInfoEntity.getJobLevelId());
        promotionEntity.setBeforeJobType(employeeInfoEntity.getJobLevelType().toString());
        promotionEntity.setUnitId(employeeInfoEntity.getUnitId());
//        if(promotionEntity.getBeginExpeditionDate()!=null&&promotionEntity.getExpeditionDays()!=null)
//        promotionEntity.setEndExpeditionDate(DateUtils.addDateDays(promotionEntity.getBeginExpeditionDate(),promotionEntity.getExpeditionDays()));

        //待审批状态
        //如果存在晋升id更新晋升信息，如果不存在插入晋升信息
        if(promotionEntity.getPromotionId()==null){
            /**
             * 每次创建都要输入创建时间
             */
            promotionEntity.setCreateTime(createTime);
            //设置考察状态初值
            promotionEntity.setExpeditionStatus(0);
            //薪资组状态初值
            promotionEntity.setIsDistribute(0);
            String url = commonController.getFileUrls(promotionVo.getFileUrl(),promotionEntity.getOid(),"晋升附件");
            promotionEntity.setFileUrl(url);
            promotionEntity.setPromotionId(snowflakeIdWorker.nextId());
            R insert = promotionService.saveE(promotionEntity);
            if (R.isOk.equals(insert.getStatus())){

                return R.ok(promotionEntity);
            }else {
                return R.error();
            }
        }else{
            if(CollectionUtils.isEmpty(promotionVo.getFileUrl())){
                promotionEntity.setFileUrl("");
            }else{
                String url =  commonController.getFileUrls(promotionVo.getFileUrl(),promotionEntity.getOid(),"晋升附件");
                promotionEntity.setFileUrl(url);
            }
            int update = promotionDao.updateById(promotionEntity);
            if (update>0){
                return R.ok(promotionEntity);
            }else {
                return R.error();
            }
        }


    }

    /**
     * 将晋升后的信息更新到员工信息
     * @param promotionEntity
     */
    @Transactional
    public void doPromotionOk(PromotionEntity promotionEntity,boolean isUpper){
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(promotionEntity.getOid());
        //专业职级
        Integer professionPromotion = 1;
        if(professionPromotion.equals(promotionEntity.getPromotionType())){
            employeeInfoEntity.setProfessionJoblevelId(promotionEntity.getAfterJobLevelId());
        }else if(isUpper){
            employeeInfoEntity.setManagementJoblevelId(promotionEntity.getAfterJobLevelId());
            RegularBpmEntity bpmEntity = new RegularBpmEntity();
            bpmEntity.setCreateTime(new Date());
            bpmEntity.setHiredate(employeeInfoEntity.getHiredate());
            bpmEntity.setOid(promotionEntity.getOid());
            bpmEntity.setCode(employeeInfoEntity.getCode());
            bpmEntity.setName(employeeInfoEntity.getName());
            bpmEntity.setJobId(promotionEntity.getAfterJobId());
            bpmEntity.setJobLevel(jobController.jobLevelMap.get(promotionEntity.getAfterJobLevelId()));
            bpmEntity.setJobLevelId(promotionEntity.getAfterJobLevelId());
            bpmEntity.setJobLevelType(Integer.parseInt(promotionEntity.getAfterJobType()));
            bpmEntity.setJobname(jobController.jobMap.get(promotionEntity.getAfterJobId()));
            bpmEntity.setOrgId(promotionEntity.getAfterOrgId());
            bpmEntity.setOrgname(jobController.orgMap.get(promotionEntity.getAfterOrgId()));
            bpmEntity.setProbationday(promotionEntity.getExpeditionDays());
            bpmEntity.setRegularDay(promotionEntity.getEndExpeditionDate());
            bpmEntity.setRegularType(2);//2:管理晋级转正
            bpmEntity.setRelationId(promotionEntity.getPromotionId());
            bpmEntity.setUnitname(jobController.orgMap.get(promotionEntity.getAfterUnitId()));
            bpmEntity.setUnitId(promotionEntity.getAfterUnitId());
            bpmEntity.setUseraccount(employeeInfoEntity.getUseraccount());
            bpmEntity.setOrgId(employeeInfoEntity.getOrgId());
            bpmEntity.setBeforeJobId(employeeInfoEntity.getJobId());
            bpmEntity.setBeforeJobLevel(jobController.jobLevelMap.get(employeeInfoEntity.getJobLevelId()));
            bpmEntity.setBeforeJobLevelId(employeeInfoEntity.getJobLevelId());
            bpmEntity.setBeforeJobName(jobController.jobMap.get(employeeInfoEntity.getJobId()));
            bpmEntity.setBeforeOrgId(employeeInfoEntity.getOrgId());
            bpmEntity.setBeforeUnitId(employeeInfoEntity.getUnitId());
            bpmEntity.setApplyTime(promotionEntity.getPromotionDate());
            bpmEntity.setBeforeUnitName(jobController.orgMap.get(employeeInfoEntity.getUnitId()));
            bpmEntity.setBeforeLevelType(employeeInfoEntity.getJobLevelType().toString());
            bpmEntity.setBeforeOrgName(jobController.orgMap.get(employeeInfoEntity.getOrgId()));
            regularBpmService.saveE(bpmEntity);
        }
        //更新岗位、职位、公司、职级信息到员工信息表
//        employeeInfoEntity.setOrgId(promotionEntity.getAfterOrgId());
        employeeInfoEntity.setJobId(promotionEntity.getAfterJobId());
        employeeInfoEntity.setJobLevelId(promotionEntity.getAfterJobLevelId());
        employeeInfoEntity.setUnitId(promotionEntity.getAfterUnitId());
        employeeInfoEntity.setJobLevelType(Integer.parseInt(promotionEntity.getAfterJobType()));

        employeeInfoService.updateByIdE(employeeInfoEntity);
        promotionEntity.setStatus(3);
        promotionService.updateByIdE(promotionEntity);
        neusoftEmployeeChangeService.uploadPromotionChange(promotionEntity);
        //判断是否重新签署
        afreshContract(promotionEntity);
    }

    private void afreshContract(PromotionEntity promotionEntity){
       boolean beforeIsBelow =  isBelowM2P4(promotionEntity.getBeforeJobLevelId());
       boolean afterIsBelow =  isBelowM2P4(promotionEntity.getAfterJobLevelId());
        ContractNewVo vo  = new ContractNewVo();
        vo.setType(ContractConst.CONTRACT_TYPE_TERMINATE);
        vo.setOid(promotionEntity.getOid());
        vo.setContractType(ContractConst.CONTRACT_MANAGER_TERMINATE);
        vo.setContractBeginDate(DateUtils.addDateDays(promotionEntity.getPromotionDate(),-1));
        boolean isNewContract = false;
       if(beforeIsBelow&&!afterIsBelow){
           vo.setOperateType(ContractConst.CONTRACT_OPERATE_PROMOTION);
           isNewContract = true;
       }else if(!beforeIsBelow&&afterIsBelow){
           vo.setOperateType(ContractConst.CONTRACT_OPERATE_DEMOTION);
           isNewContract =true;
        }
        if(isNewContract){
            List<ContractRecordEntity> list = contractRecordDao.selectList(new QueryWrapper<ContractRecordEntity>().eq("status",1).
                    eq("kind",1).eq("is_delete",0).eq("oid",promotionEntity.getOid()));
            if(!CollectionUtils.isEmpty(list)){
                ContractRecordEntity recordEntity = list.get(0);
                ContractMangerEntity mangerEntity = contractMangerService.getByIdE(recordEntity.getStartContractId());
                vo.setCompanyName(mangerEntity.getEmployerCompany());
                vo.setCompanyId(mangerEntity.getEmployerCompanyId());
            }
            vo.setRelateId(promotionEntity.getPromotionId());
            contractController.saveNewContract(vo);
        }

    }
    /**
     * 是否小于 p4/m2
     *
     * @param jobLevelId
     * @return
     */
    private Boolean isBelowM2P4(Long jobLevelId) {
        ArrayList<Long> arrayList = new ArrayList<>();
        //M1
//        arrayList.add(14517424l);
        //p3-p1
        arrayList.add(14517435l);
        arrayList.add(14517436l);
        arrayList.add(14517437l);

        if (arrayList.contains(jobLevelId)) {
            return true;
        } else {
            return false;
        }
    }


    @PostMapping("/getPromotionList")
    @ApiOperation(value="晋升列表")
    @PreAuthorize("hasAuthority('emp:plgljj:get')")
    public R<PageResult<PromotionDto>> getPromotionList (@RequestBody @Valid PromotionListVo promotionListVo,HttpServletRequest request) throws Exception{
//        List<Long> jobIds = null;
//        List<Long>  jobSystemIds = null;
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
//        //体系
//        if(!StringUtil.isNullOrEmpty(promotionListVo.getJobSystem())){
//            jobSystemIds = baseMssqlService.findSystemIdByName(promotionListVo.getJobSystem());
//        }
//        //职位
//        if(!StringUtil.isNullOrEmpty(promotionListVo.getJob())){
//            jobIds = baseMssqlService.findJobIdByJobName(promotionListVo.getJob());
//        }

        PageResult<PromotionEntityDto> result =promotionService.queryPage(promotionListVo.getPromotionType(),promotionListVo.getUserCode(),
                promotionListVo.getName(),promotionListVo.getOrgName(),promotionListVo.getDepartmentName(),
                promotionListVo.getExpeditionStatus(),promotionListVo.getIsDistribute(),orgIds,promotionListVo.getPromotionKind(),
                promotionListVo.getIsSelf(),promotionListVo.getPageNum(),promotionListVo.getPageSize(),promotionListVo.getStatus());
        List<PromotionEntityDto> promotionEntities = result.getList();
        List<PromotionDto> dtoList = getPromotionDtoList(promotionEntities);  //封装基础信息
        PageResult<PromotionDto> re = new PageResult<>();
        re.setList(dtoList);
        re.setCurrPage(result.getCurrPage());
        re.setPageSize(result.getPageSize());
        re.setTotalCount(result.getTotalCount());
        re.setTotalPage(result.getTotalPage());
        return R.ok(re);
    }

    @GetMapping("/getPromotionDetail")
    @ApiOperation(value="晋升详情")
    @PreAuthorize("hasAuthority('emp:plgljj:get')")
    public R getPromotionDetail(Long promotionId){
        PromotionEntity promotionEntity = promotionService.getByIdE(promotionId);
        if(promotionEntity==null){
            R.error("晋升信息不存在");
        }
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code",promotionEntity.getApplierCode()));
        if(employeeInfoEntity==null){
            R.error("申请人不存在");
        }
        PromotionDto promotionDto =  BeanUtilsMabach.doToDto(promotionEntity,PromotionDto.class);
//        promotionDto.setu(employeeInfoEntity.getUnitname());
        promotionDto.setApplierJob(employeeInfoEntity.getJobname());
        return R.ok(promotionDto);
    }



//    @PostMapping("/doExpedition")
//    @ApiOperation(value="单条考察期修改")
//    @SysAuthorityLog(value = "单条考察期修改")
//    @Transactional
//    @PreAuthorize("hasAuthority('emp:plgljj:update')")
//    public R doExpedition(String promotionId,Integer expeditionStatus, String beginExpeditionDate,Integer expeditionDays,
//                          HttpServletRequest request)throws  Exception{
//        PromotionEntity promotionEntity = promotionService.getByIdE(Long.parseLong(promotionId));
//        if(ObjectUtils.isEmpty(promotionEntity)){
//            R.error("晋升信息不存在");
//        }
//        //判断是否为有该公司的权限
//        R checkR = loginController.checkOrgPermission(request,promotionEntity.getBeforeUnitId(),true);
//        if(!R.isOk.equals(checkR.getStatus())){
//            return checkR;
//        }
//        promotionEntity.setExpeditionStatus(expeditionStatus);
//        Date time = DateUtils.parseDateYMDHMSS(beginExpeditionDate);
//        //如果要延长审批 审批状态依旧是0且传审批开始时间
//        if(0==expeditionStatus&&beginExpeditionDate!=null&&expeditionDays!=null){
//            promotionEntity.setBeginExpeditionDate(time);
//            promotionEntity.setExpeditionDays(expeditionDays);
//            promotionEntity.setEndExpeditionDate(DateUtils.addDateDays(time,expeditionDays));
//        }
//       int update =  promotionDao.updateById(promotionEntity);
//       if(update>0){
//           R.ok();
//       }else{
//           R.error();
//       }
//       return R.ok();
//    }

    @PostMapping("/doBatchPromotion")
    @ApiOperation(value="多条晋升")
    @SysAuthorityLog(value = "多条晋升")
    @PreAuthorize("hasAuthority('emp:plgljj:update')")
    @Transactional
    public R doBatchPromotion(@RequestBody @Valid List<PromotionVo> promotionVos,HttpServletRequest request)throws Exception{
        Integer i=0;
        String errMsg = "";
        boolean isError = false;
        PromotionBatchEntity batchEntity = new PromotionBatchEntity();
        for(PromotionVo promotionVo:promotionVos){
            try {
                R r = updatePromotion(promotionVo,request);
                //如果插入晋升信息成功更新雇佣表信息
                if(r.getStatus()==200){
                    PromotionEntity promotionEntity = (PromotionEntity) r.getData();

                    SalaryChangeEntity salaryChangeEntity = new SalaryChangeEntity();
                    salaryChangeEntity.setOid(promotionEntity.getOid());
                    salaryChangeEntity.setUnitId(promotionVo.getAfterUnitId());
                    salaryChangeEntity.setNewJobId(promotionVo.getAfterJobId());
                    salaryChangeEntity.setNewJobLevelId(promotionVo.getAfterJobLevelId());
                    salaryChangeEntity.setNewOrgId(promotionVo.getAfterOrgId());
                    if(!ObjectUtils.isEmpty(promotionVo.getAfterJobType()))
                    salaryChangeEntity.setNewJobLevelType(Integer.parseInt(promotionVo.getAfterJobType()));
                    salaryChangeEntity.setNewJobLevel(jobController.jobLevelMap.get(promotionVo.getAfterJobLevelId()));
                    //晋升调薪
                    if(promotionVo.getPromotionKind().equals(0)){
                        //专业职级晋升
                        if(promotionVo.getPromotionType().equals(1)){
                            //薪资变动
                            salaryChangeEntity.setType(SalaryConst.SALARY_TYPE_ENTRY);
                            salaryChangeEntity.setEffectiveTime(promotionEntity.getPromotionDate());
                            salaryChangeService.saveE(salaryChangeEntity);
                        }
                        doPromotionOk(promotionEntity,true);
                    }
                    //降级调薪
                    else if(promotionVo.getPromotionKind().equals(1)){
                        salaryChangeEntity.setType(SalaryConst.SALARY_TYPE_DOWNGRADE);
                        salaryChangeEntity.setEffectiveTime(promotionEntity.getPromotionDate());
                        doPromotionOk(promotionEntity,false);
                        salaryChangeService.saveE(salaryChangeEntity);
                    }

                    savePromotionBatch(promotionVo,promotionEntity,batchEntity,request,i);
                    i++;
                }else{
                    isError = true;
                    errMsg += promotionVo.getName()+",";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        if(isError){
            errMsg +="没有对应公司组权限插入失败";
            return R.error(errMsg);
        }else{
            return R.ok();
        }
    }

    /**
     * 保存批量晋升/降级批次信息
     * @param promotionVo
     * @param promotionEntity
     * @param batchEntity
     * @param request
     * @param i
     * @param size
     * @throws Exception
     */
    private void savePromotionBatch(PromotionVo promotionVo,PromotionEntity promotionEntity,
                                    PromotionBatchEntity batchEntity,HttpServletRequest request,
                                    Integer i)throws Exception{
        if(i.equals(0)){
            String fileUrl  = "";
            Integer j=1;
            if(!CollectionUtils.isEmpty(promotionVo.getFileUrl())){
                for(String url :promotionVo.getFileUrl()){
                    if(j.equals(promotionVo.getFileUrl().size())){
                        fileUrl += url ;
                    }else{
                        fileUrl += url+"," ;
                    }
                }
            }

            JSONObject userInfo = loginController.getUserInfo(request).getData();
            String name = userInfo.getString("name");
            String userCode = userInfo.getString("usercode");
            String jobname = userInfo.getString("jobname");
            String unitName = userInfo.getString("department");
            Long unitId = userInfo.getLong("depId");
            batchEntity.setCreateTime(new Date());
            batchEntity.setJobname(jobname);
            batchEntity.setType(promotionVo.getPromotionKind().equals(1)?3:promotionVo.getPromotionType());
            batchEntity.setNumber(1);
            batchEntity.setUnitId(unitId);
            batchEntity.setUnitname(unitName);
            batchEntity.setFileUrl(fileUrl);
            batchEntity.setApplyerCode(userCode);
            batchEntity.setApplyer(name);
            batchEntity.setReason(promotionVo.getReason());
            batchEntity.setPromotionCode(promotionVo.getPromotionCode());
            promotionBatchService.saveE(batchEntity);
        }else{
            batchEntity.setNumber(batchEntity.getNumber()+1);
            promotionBatchService.updateByIdE(batchEntity);
        }
        PromotionBatchGroupEntity groupEntity = new PromotionBatchGroupEntity();
        groupEntity.setBatchId(batchEntity.getId());
        groupEntity.setPromotionId(promotionEntity.getPromotionId());
        groupEntity.setCreateTime(new Date());
        promotionBatchGroupService.saveE(groupEntity);
    }

    @PostMapping("/updateSalaryInfo")
    @ApiOperation(value="更新薪资组")
    @SysAuthorityLog(value = "更新薪资组")
    @Transactional
    @PreAuthorize("hasAuthority('emp:salary:update')")
    public R updateSalaryInfo(Long promotionId,@RequestBody  SalaryGroupVo salaryGroupVo,
                              @RequestBody SalaryDto salaryDto,HttpServletRequest request)throws Exception{
        PromotionEntity promotionEntity = promotionService.getByIdE(promotionId);
        if(ObjectUtils.isEmpty(promotionEntity)){
            return R.error("信息不存在无法更新薪资组！");
        }

        salaryGroupVo.setOid(promotionEntity.getOid());
        salaryGroupVo.setSalaryGroupId(promotionEntity.getSalaryGroupId());
        R salaryGroupR = salaryController.updateSalaryGroup(salaryGroupVo,request);
        if(200!=salaryGroupR.getStatus()){
            return salaryGroupR;
        }
        //更新固定月薪、绩效到员工信息表
        salaryDto.setMonthlySalary(promotionEntity.getMonthlySalary());
        salaryDto.setPerformance(promotionEntity.getPerformance());
        R salaryR = salaryController.updateSalaryByOid(salaryDto,request);
        promotionEntity.setIsDistribute(1);
        promotionService.updateByIdE(promotionEntity);
        return R.ok();
    }


    @PostMapping("/findEmpByUserCodes")
    @ApiOperation(value="根据工号集合查找员工")
    public R<List<EmployeeInfoEntity>> findEmpByUserCodes(  String[] str){


        if (str==null||str.length==0){
            return R.error();
        }
        List<String> list = Arrays.asList(str);
        ArrayList<EmployeeInfoEntity> employeeInfoEntities = new ArrayList<>();
        for (Object userCode : list) {
            /**
             * 先去mysql主库中查询员工主表，如果查不到再去mssql中查找
             */
            EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code", userCode.toString()).eq("is_delete", 0));

            if (ObjectUtils.isEmpty(employeeInfoEntity)){
                employeeInfoEntity = commonService.finEmpFromMssqlByCode(userCode.toString());
            }
            if(!ObjectUtils.isEmpty(employeeInfoEntity)){
                employeeInfoEntities.add(employeeInfoEntity);
            }
        }
        List<EmployeeInfoDto> employeeInfoDtoList=new ArrayList<>();
        for(EmployeeInfoEntity employeeInfoEntity:employeeInfoEntities){
            EmployeeInfoDto employeeInfoDto = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeInfoDto.class);
            if(employeeInfoDto.getJobId()!=null) employeeInfoDto.setJobname(jobController.getJobName(employeeInfoDto.getJobId()));
            if(employeeInfoDto.getOrgId()!=null) employeeInfoDto.setOrgname(jobController.getOrgNameById(employeeInfoDto.getOrgId()));
            if(employeeInfoDto.getUnitId()!=null) employeeInfoDto.setUnitname(jobController.getOrgNameById(employeeInfoDto.getUnitId()));
            employeeInfoDtoList.add(employeeInfoDto);
        }
        return R.ok(employeeInfoDtoList);
    }

    @GetMapping("/deletePromotion")
    @ApiOperation(value="删除单条晋升")
    @SysAuthorityLog(value = "删除单条晋升")
    @PreAuthorize("hasAuthority('emp:plgljj:update')")
    @Transactional
    public R deletePromotion(@RequestParam(value="promotionId") Long promotionId){
        promotionService.removeOneById(promotionId);
        return R.ok();
    }

    @GetMapping("/batchDelete")
    @ApiOperation(value="批量删除单条晋升")
    @SysAuthorityLog(value = "批量删除单条晋升")
    @PreAuthorize("hasAuthority('emp:plgljj:update')")
    @Transactional
    public R batchDelete(Long[] promotionIds){
        for(Long id :promotionIds){
            promotionService.removeOneById(id);
        }
        return R.ok();
    }

    public List<PromotionDto> getPromotionDtoList(List<PromotionEntityDto> entityList){
        List<PromotionDto> dtoList = new ArrayList<>();
        for(PromotionEntityDto promotionEntity:entityList){
            PromotionDto d = BeanUtilsMabach.doToDto(promotionEntity,PromotionDto.class);
            //            根据id去换缓存中获取组织名称
            String beforeOrgName = jobController.getOrgNameById(promotionEntity.getBeforeOrgId());
            String beforeUnitName = jobController.getOrgNameById(promotionEntity.getBeforeUnitId());
            //根据id去换缓存中获取岗位名称
            String beforeJobName = jobController.getJobName(promotionEntity.getBeforeJobId());
            String applierJob = jobController.getJobName(promotionEntity.getApplyJobId());
            String applierOrg = jobController.getOrgNameById(promotionEntity.getApplyOrgId());
            String applierUnit = jobController.getOrgNameById(promotionEntity.getApplyUnitId());
            String applierJobLevel = jobController.getJobLevelNameById(promotionEntity.getApplyJobLevelId());

            //根据id去换缓存中获取职级名称
            String beforeJobLevelName = jobController.getJobLevelNameById(promotionEntity.getBeforeJobLevelId());
            d.setBeforeOrgname(beforeOrgName);
            d.setBeforeUnitName(beforeUnitName);
            d.setBeforeJobName(beforeJobName);
            d.setBeforeJobLevel(beforeJobLevelName);
            if(!ObjectUtils.isEmpty(promotionEntity.getAfterOrgId())){
                String afterOrgName = jobController.getOrgNameById(promotionEntity.getAfterOrgId());
                d.setAfterOrgname(afterOrgName);
            }
            if(!ObjectUtils.isEmpty(promotionEntity.getAfterUnitId())){
            String afterUnitName = jobController.getOrgNameById(Long.valueOf(promotionEntity.getAfterUnitId()));
            d.setAfterUnitName(afterUnitName);
            }
            //根据id去换缓存中获取岗位名称
            if(!ObjectUtils.isEmpty(promotionEntity.getAfterJobId())){
            String afterJobName = jobController.getJobName(promotionEntity.getAfterJobId());
            d.setAfterJobName(afterJobName);
            }
            if(!ObjectUtils.isEmpty(promotionEntity.getAfterJobLevelId())){
            String afterJobLevel = jobController.getJobLevelNameById(promotionEntity.getAfterJobLevelId());
            d.setAfterJobLevel(afterJobLevel);
            d.setApplierJobLevel(afterJobLevel);
            }

            d.setApplierJob(applierJob);
            d.setApplierUnit(applierUnit);
            d.setApplierOrg(applierOrg);
            d.setApplierJobLevel(applierJobLevel);
            d.setApplierName(promotionEntity.getApplyName());
            dtoList.add(d);

        }
        return dtoList;
    }

    @PostMapping("/getBatchList")
    @ApiOperation(value="批量晋升批次列表")
    @PreAuthorize("hasAuthority('emp:plgljj:get')")
    public R<PageResult<PromotionBatchEntity>> getBatchList(@RequestBody @Valid PromotionBatchVo vo,HttpServletRequest request)throws Exception{
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
       PageResult pageResult = promotionBatchService.queryPage(vo.getPromotionCode(),vo.getUserCode(),vo.getType(),null,null,null,orgIds,vo.getPageNum(),vo.getPageSize());
        return R.ok(pageResult);
    }

    @PostMapping("/getBatchDetail")
    @ApiOperation(value="批量晋升批次详情")
    @PreAuthorize("hasAuthority('emp:plgljj:get')")
    public R<PromotionBatchDto> getBatchDetail(String id){
        if(StringUtils.isEmpty(id)){
            return  R.error("批次id不存在！");
        }
        PromotionBatchEntity batchEntity = promotionBatchService.getByIdE(Long.parseLong(id));
        if(ObjectUtils.isEmpty(batchEntity)){
            return R.error("批次信息不存在！");
        }
        PromotionBatchDto batchDto = BeanUtilsMabach.doToDto(batchEntity,PromotionBatchDto.class);
        List<PromotionEntity> list = promotionBatchGroupDao.getPromtionBtachList(id);
        if(!CollectionUtils.isEmpty(list)){
            List<PromotionDto> reList = new ArrayList<>();
            for(PromotionEntity entity:list){
                PromotionDto dto = BeanUtilsMabach.doToDto(entity,PromotionDto.class);
                dto.setAfterJobName(jobController.jobMap.get(entity.getAfterJobId()));
                String afterUnit = jobController.orgMap.get(entity.getAfterUnitId());
                dto.setAfterUnitName(afterUnit);
                String beforeUnit = jobController.orgMap.get(entity.getBeforeUnitId());
                dto.setBeforeUnitName(beforeUnit);
                dto.setBeforeJobName(jobController.jobMap.get(entity.getBeforeJobId()));
                dto.setBeforeOrgname(jobController.orgMap.get(entity.getBeforeOrgId()));
                dto.setAfterOrgname(jobController.orgMap.get(entity.getAfterOrgId()));
                dto.setBeforeJobLevel(jobController.jobLevelMap.get(entity.getBeforeJobLevelId()));
                dto.setAfterJobLevel(jobController.jobLevelMap.get(entity.getAfterJobLevelId()));
                reList.add(dto);
            }
            batchDto.setPromotionList(reList);
        }
        return R.ok(batchDto);
    }



}
